﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace Universe.OneC
{
    internal class ObjectsCache : IDisposable
    {
        private Adapter1C _adapter;

        private Dictionary<string, object> _cache = new Dictionary<string, object>();

        public ObjectsCache(Adapter1C adapter)
        {
            _adapter = adapter;
        }

        public object GetObject(string name)
        {
            object ret;
            if (!_cache.TryGetValue(name, out ret))
            {
                ret = _adapter.NewObject(name);
                _cache[name] = ret;
            }

            return ret;
        }

        public void Dispose()
        {
            List<object> list = new List<object>(_cache.Values);
            _cache.Clear();
            foreach (object o in list)
            {
                if (o != null && Marshal.IsComObject(o))
                    Marshal.ReleaseComObject(o);
            }
        }
    }
}
